import threading
import time
num = 0
l1 = threading.Lock()
def my_add():
    global num
    with l1:
        temp = num
        time.sleep(0.0001)  # 增加上下文切换概率
        num = temp + 1

def my_sub():
    global num
    with l1:
        temp = num
        time.sleep(0.0001)  # 增加上下文切换概率
        num = temp - 1

t_l = []
for i in range(0, 10000): # 增加线程数量和运行次数
    if i%2==0:
        t_l.append(threading.Thread(target=my_add))
    else:
        t_l.append(threading.Thread(target=my_sub))

for t in t_l:
    t.start()
for t in t_l:
    t.join()
print(num)


